from django.contrib import admin
from django.core.exceptions import PermissionDenied
from .models import *

admin.site.site_title = '母婴后台系统'
admin.site.site_header = "母婴电商后台管理系统"
admin.site.index_title = "母婴平台管理"


@admin.register(Types)
class TypesAdmin(admin.ModelAdmin):
    list_display = [x for x in list(Types._meta._forward_fields_map.keys())]
    search_fields = ['firsts', 'seconds']
    list_filter = ['firsts']


@admin.register(CommodityInfos)
class CommodityInfosAdmin(admin.ModelAdmin):
    def format_price(self, obj):
        return f"￥{obj.price}"
    format_price.short_description = '价格'

    def get_list_display(self, request):
        base_fields = ['id', 'name', 'sizes', 'types']
        if request.user.is_superuser:
            base_fields.extend(['format_price', 'discount'])
        return base_fields

    def get_list_editable(self, request):
        return ['name']

    def get_changelist_instance(self, request):
        cl = super().get_changelist_instance(request)
        cl.list_editable = self.get_list_editable(request)
        return cl

    def get_fieldsets(self, request, obj=None):
        if request.user.is_superuser:
            return (
                ('商品信息', {
                    'fields': ('name', 'sizes', 'types', 'price', 'discount')
                }),
                ('收藏数量', {
                    'classes': ('collapse',),
                    'fields': ('likes',),
                }),
            )
        else:
            return (
                ('商品信息', {
                    'fields': ('name', 'sizes', 'types')
                }),
                ('收藏数量', {
                    'classes': ('collapse',),
                    'fields': ('likes',),
                }),
            )

    search_fields = ['name']
    date_hierarchy = 'create'
    ordering = ['id']
    sortable_by = ('price', 'discount')
    list_filter = ['types']
    list_per_page = 100
    list_max_show_all = 200
    save_as = True
    actions_on_top = False
    actions_on_bottom = True

    def formfield_for_dbfield(self, db_field, **kwargs):
        if db_field.name == 'types':
            db_field.choices = [(x['seconds'], x['seconds']) for x in Types.objects.values('seconds')]
        return super().formfield_for_dbfield(db_field, **kwargs)

    def get_queryset(self, request):
        qs = super().get_queryset(request)
        if request.user.is_superuser:
            return qs
        else:
            return qs.filter(id__lt=2)

    def formfield_for_choice_field(self, db_field, request, **kwargs):
        if db_field.name == 'types':
            kwargs['choices'] = (('童装', '童装'), ('进口奶粉', '进口奶粉'))
        return super().formfield_for_choice_field(db_field, request, **kwargs)

    def save_model(self, request, obj, form, change):
        if change:
            user = request.user.username
            name = self.model.objects.get(pk=obj.pk).name
            types = form.cleaned_data['types']
            with open("d://log.txt", 'a', encoding='utf-8') as f:
                f.write(f"{name}商品类型：{types}被{user}修改\n")
        super().save_model(request, obj, form, change)

    def get_datas(self, request, queryset):
        temp = []
        for d in queryset:
            t = [d.name, d.types, str(d.discount)]
            temp.append(t)
        with open("d://data.txt", 'a', encoding='utf-8') as f:
            for t in temp:
                f.write(",".join(t) + '\n')
        self.message_user(request, "数据导出成功")

    get_datas.short_description = "导出所选数据"
    actions = ['get_datas']

    def has_delete_permission(self, request, obj=None):
        return request.user.is_superuser

    def delete_model(self, request, obj):
        if not request.user.is_superuser:
            raise PermissionDenied
        super().delete_model(request, obj)

    def delete_queryset(self, request, queryset):
        if not request.user.is_superuser:
            raise PermissionDenied
        super().delete_queryset(request, queryset)

    def get_actions(self, request):
        actions = super().get_actions(request)
        if not request.user.is_superuser and 'delete_selected' in actions:
            del actions['delete_selected']
        return actions
